package cn.yoshii.ad.adserver.chang

import cn.yoshii.ad.adserver.chang.ad.ChangAd
import cn.yoshii.ad.adserver.chang.rta.ChangRta
import cn.yoshii.ad.adserver.config.AdProperties
import cn.yoshii.ad.adserver.model.data.AdType
import cn.yoshii.ad.adserver.model.entity.AdInfo
import cn.yoshii.ad.adserver.model.entity.AdInfoRepository
import cn.yoshii.ad.adserver.param.DeviceRequest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Service

/**
 * @author xiang
 * @Date 2024/2/16 13:35
 **/
@Service
class ChangAdService {

    companion object {
        private const val TAG = "ChangAdService"
    }

    @Autowired
    private lateinit var adInfoRepository: AdInfoRepository

    @Autowired(required = false)
    private lateinit var adProperties: AdProperties

    fun getAds(request: DeviceRequest): List<AdInfo> {
        val rta = if (adProperties.testing) {
            ChangRta.fakeRta()
        } else {
            ChangRta.rta(request)
        }
        val accepted = rta.filter { it.accept }
        val ads = ArrayList<AdInfo>()
        accepted.forEach {
            it.promotionType.toAdType()?.let { type ->
                ads.addAll(adInfoRepository.findAllByAdType(type))
            }
        }
        return ads
    }

    @Async("taskExecutor")
    fun report(request: DeviceRequest, packId: String, requestId: String) {
        val callbackUrl = "${adProperties.callback}?requestId=$requestId"
        ChangAd.report(request, packId, requestId, callbackUrl)
    }

    private fun Int.toAdType(): AdType? {
        return when (this) {
            1 -> AdType.KS_LX
            2 -> AdType.JS_LX
            3 -> AdType.KS_LH
            4 -> AdType.JS_LH
            else -> null
        }
    }
}